package com.uniview.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uniview.dao.EmployeesDao;
import com.uniview.dao.ResourceRoleDao;
import com.uniview.dao.UserRoleDao;
import com.uniview.entity.po.Employees;
import com.uniview.entity.po.ResourceRole;
import com.uniview.entity.po.UserRole;
import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.QueryBuilder;
import com.uniview.service.EmployeesService;

@Service("employeesService")
public class EmployeesServiceImpl implements EmployeesService {

	@Autowired
	private EmployeesDao employeesDao;
	@Autowired
	private UserRoleDao userRoleDao;
	@Autowired
	private ResourceRoleDao resourceRoleDao;

	private Logger logger = Logger.getLogger(EmployeesServiceImpl.class);

	@Override
	public int countEmployeesByOrgNameWithoutCharge(String orgName, String workNo, String dept) {
		try {
			return employeesDao.countEmployeesByOrgNameWithoutCharge(orgName, workNo, dept);
		} catch (Exception e) {
			logger.error("========统计部门所属员工异常", e);
		}
		return 0;
	}

	@Override
	public boolean deleteAll() {
		try {
			return employeesDao.deleteAll();
		} catch (Exception e) {
			logger.error("清空人员数据异常", e);
		}
		return false;
	}

	@Override
	public boolean deleteEmployeesById(int eId) {
		try {
			return employeesDao.deleteEmployeesById(eId);
		} catch (Exception e) {
			logger.error("根据ID删除人员信息异常", e);
		}
		return false;
	}

	@Override
	public List<Employees> findAll() {
		try {
			return employeesDao.findAll();
		} catch (Exception e) {
			logger.error("查询全部人员信息异常", e);
		}
		return null;
	}

	@Override
	public Employees findEmployeesByEmpCodeWithLike(String empCode) {
		try {
			return employeesDao.findEmployeesByEmpCodeWithLike(empCode);
		} catch (Exception e) {
			logger.error("========查询员工异常", e);
		}
		return null;
	}

	@Override
	public Employees findEmployeesById(int eId) {
		try {
			return employeesDao.findEmployeesById(eId);
		} catch (Exception e) {
			logger.error("根据ID查询人员信息异常", e);
		}
		return null;
	}

	@Override
	public Employees findEmployeesByName(String userName) {
		try {
			List<Employees> list = employeesDao.findEmployeesByName(userName.toUpperCase());
			if (list != null && !list.isEmpty()) {
				if (list.size() != 1) {
					logger.error("=================根据账号查询雇员记录不止一条，请确认记录唯一性");
				} else {
					return list.get(0);
				}
			} else {
				logger.error("=================根据账号查询雇员记录为0");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<Employees> findEmployeesByOrgName(String orgName) {
		String parent = "";
		if (!orgName.endsWith("/")) {
			parent = orgName + "/";
		} else {
			parent = orgName;
			orgName = orgName.substring(0, orgName.length() - 1);
		}
		String sql = "select * from un_employees t where (t.OrgName = '" + orgName + "' or t.OrgName like '%" + parent + "%') and t.Remark <> 3";

		logger.debug("========sql:" + sql);

		try {
			return employeesDao.findBySql(sql);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("根据部门名称查询所属员工");
			return null;
		}
	}

	@Override
	public List<Employees> findEmployeesByUpdateTime(String beginDate, String endDate) {
		try {
			return employeesDao.findEmployeesByUpdateTime(beginDate, endDate);
		} catch (Exception e) {
			logger.error("根据更新日期查询人员信息异常", e);
		}
		return null;
	}

	@Override
	public Employees findEmployeesByWorkNo(String workNo) {
		try {
			return employeesDao.findEmployeesByWorkNo(workNo);
		} catch (Exception e) {
			logger.error("获取员工信息异常", e);
		}
		return null;
	}

	@Override
	public String findEmployeesIdByName(String name) {
		try {
			return employeesDao.findEmployeesIdByName(name);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取员工ID异常", e);
		}
		return null;
	}

	@Override
	public List<Employees> findEmployessByINTJournalId(int jid) {
		try {
			return employeesDao.findEmployessByINTJournalId(jid);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查詢国际日报的可視范圍對應的员工");
		}
		return null;
	}

	@Override
	public List<Employees> findEmployessByJournalId(int jid) {
		try {
			return employeesDao.findEmployessByJournalId(jid);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查詢日報的可視范圍對應的员工");
		}
		return null;
	}

	@Override
	public List<Employees> findEmployessByManhoursId(int jid) {
		try {
			return employeesDao.findEmployessByManhoursId(jid);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查詢工时管理的可視范圍對應的员工");
		}
		return null;
	}

	@Override
	public Pager<Employees> findPageEmployees(int pageNo, int pageSize) {
		try {
			return employeesDao.findPageEmployees(pageNo, pageSize);
		} catch (Exception e) {
			logger.error("分页查询人员信息异常", e);
		}
		return null;
	}

	@Override
	public Pager<Employees> findPageEmployees(QueryBuilder queryBuilder, int pageNo, int pageSize) {
		try {
			return employeesDao.findPagerByQueryBuilder(queryBuilder, pageNo, pageSize);
		} catch (Exception e) {
			logger.error("分页查询雇员异常", e);
		}
		return null;
	}

	/**
	 * 查询指定部门的下属员工
	 *
	 * @param orgName
	 * @param workNo
	 * @return
	 * @throws Exception
	 */
	public List<Employees> findPagerEmployeesByOrgNameWithoutCharge(String orgName, String workNo, String dept) {
		try {
			return employeesDao.findPagerEmployeesByOrgNameWithoutCharge(orgName, workNo, dept);
		} catch (Exception e) {
			logger.error("========查询部门所属员工异常", e);
		}
		return null;
	}

	@Override
	public List<Employees> findPagerEmployeesByOrgNameWithoutCharge(String orgName, String workNo, String dept,
																	int pageNo, int pageSize) {
		try {
			return employeesDao.findPagerEmployeesByOrgNameWithoutCharge(orgName, workNo, dept, pageNo, pageSize);
		} catch (Exception e) {
			logger.error("========查询部门所属员工异常", e);
		}
		return null;
	}

	@Override
	public Long getTotalRows() {
		try {
			return employeesDao.findTotalRow();
		} catch (Exception e) {
			logger.error("获取人员总数异常", e);
		}
		return null;
	}

	@Override
	public Integer getTotalRowsByUpdateTime(String beginDate, String endDate) {
		try {
			return employeesDao.getTotalRowsByUpdateTime(beginDate, endDate);
		} catch (Exception e) {
		}
		return 0;
	}

	@Override
	public int saveEmployees(Employees employees) {
		try {
			return employeesDao.saveEmployees(employees);
		} catch (Exception e) {
			logger.error(" 保存人员信息异常", e);
		}
		return 0;
	}

	@Override
	public void saveEmployeesBySql(List<Employees> list, int batchNum) {
		try {
			employeesDao.saveEmployees(list, batchNum);
		} catch (Exception e) {
			logger.error("保存人员信息异常", e);
		}
	}

	@Override
	public void SaveOrUpdateEmployees(List<Employees> list) {
		for (Employees employees : list) {
			try {
				boolean flag = employeesDao.checkEmployeeByEmpCode(employees.getEmpCode());
				logger.info("用户[" + employees.getEmpCode() + "]是否已存在: " + flag);
				if (flag) {
					logger.info("========================更新员工[" + employees.getEmpCode() + "]");
//					Employees emp = employeesDao.findEmployeesByWorkNo(employees.getEmpCode());
					Employees emp = employeesDao.findEmployeesByEmpCodeWithoutRemark(employees.getEmpCode());
					if (null != emp) {
						employees.seteId(emp.geteId());
						employeesDao.updateEmployees(employees);
					}
				} else {
					logger.info("========================新增员工[" + employees.getEmpCode() + "]");
					employeesDao.saveEmployees(employees);
				}
			} catch (Exception e) {
				logger.error("==================同步员工【" + employees.getEmpName() + "】更新信息到本地失败！！！", e);
				e.printStackTrace();
			}
		}

	}

	@Override
	public boolean updateEmployees(Employees employees) {
		try {
			return employeesDao.updateEmployees(employees);
		} catch (Exception e) {
			logger.error("更新人员信息异常", e);
		}
		return false;
	}

	@Override
	public boolean updateEmployees(List<Employees> list) {
		try {
			return employeesDao.updateEmployees(list);
		} catch (Exception e) {
			logger.error("少批量更新人员信息异常", e);
		}
		return false;
	}

	@Override
	public boolean updateLeaveEmployees(int eId, Date updateDate) {
		try {
			return employeesDao.updateLeaveEmployees(eId, updateDate);
		} catch (Exception e) {
			logger.error("更新离职人员信息异常", e);
		}
		return false;
	}

	@Override
	public List<Employees> findEmployeesByCondition(String empNameOrCode,
													String phone, String bindType, Integer roleId) {
		List<Employees>  list = new ArrayList<Employees>();
		try {
			list = employeesDao.findEmployeesByCondition(empNameOrCode, phone, bindType, roleId);
		} catch (Exception e) {
			logger.error("查询人员信息异常..............findEmployeesByCondition", e);
		}
		return list;
	}

	public List<Employees> findBindedOrUnbindEmployeesList(String bindType,
														   Integer roleId,String empName) {
		List<Employees>  list = new ArrayList<Employees>();
		try {
			list = employeesDao.findBindedOrUnbindEmployeesList(bindType, roleId,empName);
		} catch (Exception e) {
			logger.error("查询人员信息异常..............findBindedOrUnbindEmployeesList", e);
		}
		return list;
	}

	@Override
	@Transactional
	public boolean bindUserRole(String empIds, Integer roleId) {
		try {
			if(!StringUtils.isBlank(empIds) && roleId != null){
				String[] idsArr = empIds.split(",");
				for(String id:idsArr){
					Employees employees = employeesDao.findEmployeesById(Integer.parseInt(id));
					UserRole userRole = new UserRole();
					userRole.setCreateDate(new Date());
					userRole.setDeptName(employees.getOrgName());
					userRole.setPhone(employees.getPhone());
					userRole.setRoleId(roleId);
					userRole.setUserId(""+employees.getEmpCode());
					userRole.setUserName(employees.getEmpName());
					userRoleDao.saveUserRole(userRole);
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean unbindUserRole(String  userId, Integer roleId) {
		boolean flag = false;
		try {
			flag = userRoleDao.delByUserIdAndRoleId(userId,roleId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	@Transactional
	public boolean saveRoleMenuBindInfo(String bindIds,String unbindIds,Integer roleId){
		try {
			String[] bindIdArr = bindIds.split(",");//选中的菜单id
			String[] unbindIdArr = unbindIds.split(",");//未选中的菜单id
			for(String bindId:bindIdArr){
				if(StringUtils.isNotBlank(bindId.trim())){
					Integer menuId = Integer.parseInt(bindId);
					ResourceRole resourceRole = resourceRoleDao.findByMenuIdAndRoleId(menuId, roleId);
					if(resourceRole == null){
						ResourceRole entity = new ResourceRole();
						entity.setMenuId(menuId);
						entity.setRoleId(roleId);
						resourceRoleDao.save(entity);
					}
				}
			}
			for(String unbindId:unbindIdArr){
				if(StringUtils.isNotBlank(unbindId.trim())){
					Integer menuId = Integer.parseInt(unbindId);
					resourceRoleDao.delByMenuIdAndRoleId(menuId, roleId);
				}
			}
			return true;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public Pager<Employees> findAllEmployeesByPage(String empCode, String dept, int pageNo, int pageSize)
			throws Exception {
		return employeesDao.findAllEmployeesByPage(empCode, dept, pageNo, pageSize);
	}
	
	@Override
	public Pager<Employees> findAllEmployeesByPage(String empCode, int pageNo, int pageSize)
			throws Exception {
		String sql = "from Employees where 1=1 ";
		if (StringUtils.isNotBlank(empCode)) {
			sql += " and (UPPER(EmpCode) like '%" + empCode.toUpperCase() + "%' or EmpName like '%"+empCode+"%')";
		}
		return employeesDao.findPagerByQuery(pageNo, pageSize, sql);
	}

	@Override
	public Pager<Employees> findEmployeesBySearch(String searchStr, String mangerNo, Integer page, Integer limit) throws Exception {
		return employeesDao.findEmployeesBySearch(searchStr, mangerNo, page, limit);
	}

}
